package com.huluobo.a2205kotlinjetpackdemo.lifecycle

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.huluobo.a2205kotlinjetpackdemo.R

class ADActivity2 : AppCompatActivity() {
    lateinit var adManager: ADManager
    private lateinit var adViewModel: ADViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_adactivity2)

        val time = findViewById<TextView>(R.id.time)
        val cancel = findViewById<Button>(R.id.cancel)
        //ViewModel不是new出来的,所以他的状态不会发生改变,当Activity的生命周期发生变化的时候,
        // 不会影响ViewModel,也就是ViewModel不会新建,也不会销毁
        adViewModel = ViewModelProvider(this)[ADViewModel::class.java]

        adManager = ADManager(adViewModel)
        //观察者是ADManager,被观察者是当前的Activity(ComponentActivity已经实现了被观察者接口)
        //通过  lifecycle.addObserver(adManager) 产生了订阅关系
        //观察者模式三要素已经齐全
        //产生订阅关系
        lifecycle.addObserver(adManager)



        //观察ViewModel中LiveData的数据变化
        adViewModel.timingResult.observe(this) {
            time.text = "广告剩余时间:${it / 1000}秒"
            //当倒计时产生变化的时候,把已经变化的值保存到Vm当中
            adViewModel.timing  = it
            if (it / 1000 <= 1) {
                val intent = Intent(this@ADActivity2, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
//        adManager.adManagerListener = object : ADManager.ADManagerListener {
//            override fun timing(second: Int) {
//                time.text = "广告剩余时间:${second}秒"
//                //每当倒计时时,都把倒计时的秒保存到viewModel中
//                adViewModel.timing = (second * 1000).toLong()
//            }
//
//            override fun finish() {
//                val intent = Intent(this@ADActivity2, MainActivity::class.java)
//                this@ADActivity2.startActivity(intent)
//                this@ADActivity2.finish()
//            }
//        }

        cancel.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

//    //当activity产生某些生命周期的变化时,会调用该方法
//    override fun onSaveInstanceState(outState: Bundle) {
//        super.onSaveInstanceState(outState)
//        outState.putLong("time", timing)
//    }
}